<?php

define("RES_FOLDER", "../res/");
define("FONTS_FOLDER", "fonts/");
error_reporting(E_ALL);

class Image
{
	// CONSTRUCTEUR
	
	public function __construct()
	{
	
	}
	
	
	// METHODES PUBLIQUES
	
	public function imgBigToSmall($source, $destination, $new_width, $new_height)
	{
		$ext_authorize = array("gif" => 1, 
							   "jpg" => 2,
							   "jpeg" => 2,
							   "png" => 3);
		
		if (file_exists($source))
		{
			list($width, $height, $type, $attr) = getimagesize($source);
			
			if($this->verifExtension($type, $ext_authorize))
			{
				$ratio = $this->getRatio($width, $new_width, $height, $new_height);
				
				//La nouvelle image est plus petite que l'image source, on la redimenssione.
				if($ratio > 1) 
				{
					$new_width = $width / $ratio;
					$new_height = $height / $ratio;
					
					// Image vide à la nouvelle dimension
					$thumb = imagecreatetruecolor($new_width, $new_height);
					
					switch ($type)
					{
						case 1: 
							$source = imagecreatefromgif($source);
							break;
						case 2: 
							$source = imagecreatefromjpeg($source);
							break;
						case 3: 
							$source = imagecreatefrompng($source);
							break;
					} 
					
					// Copie de l'image d'origine dans une nouvelle image
					imagecopyresampled($thumb, $source, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
					imagejpeg($thumb,$destination, 100);
					
					imagedestroy($thumb); // Detruit la ressource de l'image vide
					imagedestroy($source); // Detruit la ressource de l'image source
					
					return true;
				}
				else 
				{
					copy($source,$destination); //L'image est plus petite que l'image source, on se contente de la copier.
					return true;
				}
			}
			else return false;
		}
		else return false;
		
	}
	
	public function CreateCaptcha($chaine)
	{
		$image = imagecreate(150, 40);

		$blanc = imagecolorallocate($image, 255, 255, 255);
		$noir = imagecolorallocate($image, 0, 0, 0);
		
		imagefill($image, 0, 0, $blanc);
		
		if (!empty($chaine)) 
		{
			for ($i = 0; $i < strlen($chaine); $i++)
			{
				$r = rand(0, 100);
				$g = rand(0, 100);
				$b = sqrt(100 * 100 - $r * $r - $g * $g);
				$couleur = imagecolorallocate($image, $r, $g, $b);
				imagettftext($image, rand(25,30), rand (-15,15), 10 + 20 * $i + rand(0,5), 27 + rand(0,10), $couleur, RES_FOLDER.FONTS_FOLDER."dum1.ttf", $chaine[$i]);
			}
		}
		
		imagepng($image);
		imagedestroy($image);
	}
	
	// METHODES PRIVEES
	
	private function getRatio($width, $new_width, $height, $new_height)
	{
		return max($width / $new_width, $height / $new_height);
	}
	
	private function verifExtension($type, $extensions)
	{
		return(in_array($type, $extensions));
	}
}
?>